<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="getfastWeather"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="id"
  >
    <template #toolbars>
      <Space>
        <b-button
          icon="delete"
          :disabled="!selectKeys?.length"
          @click="onDelete"
          code="weatherDrill:remove"
          >删除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button
        @click="() => onView(record)"
        type="link"
        icon="detail"
        code="drillPushTotalLog:query"
        >记录</b-button
      >
    </template>
    <template #info="{ record }">
      <div class="eewMessage">
        <div>
          <div style="flex: 1">事件:</div>
          <div style="flex: 3">{{ record.head || '--' }}</div>
        </div>
        <div>
          <div style="flex: 1">经度:</div>
          <div style="flex: 3">{{ record.longitude || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">经度:</div>
          <div style="flex: 3">{{ record.latitude || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">地名:</div>
          <div style="flex: 3">{{ record.address || '--' }}</div>
        </div>
        <div>
          <div style="flex: 1">预警时间:</div>
          <div style="flex: 3">{{ record.issueTime || '--' }}</div>
        </div>
        <div>
          <div style="flex: 1">解除时间:</div>
          <div style="flex: 3">{{ record.relieveTime || '--' }}</div>
        </div>
      </div>
    </template>
    <template #drillProjectVOS="{ record }">
      <Tree
        style="height: 130px; overflow-y: auto"
        :tree-data="record.drillProjectVOS"
        defaultExpandAll
        :fieldNames="{
          children: 'children',
          title: 'name',
          key: 'key',
        }"
      ></Tree>
    </template>
  </ProTable>
  <FormModal :items="items">
    <template #details>
      <div class="modal_table_only">
        <ProTable
          :fetchListApi="_pushTotalLog"
          hideSearch
          :columns="modalColumns"
        >
          <template #pushBy="{ record }">
            <span style="color: #409eff">{{ record.pushBy }}</span>
          </template>
          <template #operation="{ record }">
            <b-button
              @click="() => onModalView(record)"
              type="link"
              icon="detail"
              >查看</b-button
            >
            <b-button @click="() => onMessage(record)" type="link" icon="detail"
              >报文</b-button
            >
          </template>
        </ProTable>
      </div>
    </template>
  </FormModal>

  <FormModal2 :items="items">
    <template #details>
      <ProTable
        :fetchListApi="_weatherlogList"
        hideSearch
        :height="200"
        :columns="pushColumns"
      >
        <template #pushStatus="{ record }">
          <span v-if="record.pushStatus == '1'" style="color: #67c23a"
            >成功</span
          >
          <span v-else style="color: #f56c6c">失败</span>
        </template>

        <template #onlineStatus="{ record }">
          <Tag :color="record.onlineStatus == 1 ? 'success' : 'danger'">{{
            record.onlineStatus == 1 ? '在线' : '离线'
          }}</Tag>
        </template>
      </ProTable>
    </template>
  </FormModal2>

  <!-- 报文 -->
  <FormModal3 :items="items">
    <template #details>
      <JsonViewer
        :value="messageData"
        :expand-depth="5"
        style="background: transparent"
        :copyable="{ copyText: '复制', copiedText: '已复制!' }"
        sort
      ></JsonViewer>
    </template>
  </FormModal3>
</template>

<script setup lang="tsx">
import { computed, onMounted, ref } from 'vue';
import { Modal, Space, Tag, Tree } from 'ant-design-vue';
import { pick } from 'lodash-es';
import JsonViewer from 'vue-json-viewer';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import {
  deleteFastWeatherWarning,
  getfastWeather,
  pushTotalLog,
  weatherlogList,
} from '@/api/push';
import { drillsStore } from '../store';

const { refreshStore, levelCodeEnum, typeCodeEnum } = drillsStore();
const tableRef = ref();

const init = () => {
  refreshStore.weatherDrill();
};

init();
const messageData = ref({});
const selectKeys = ref<number[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '事件ID',
    dataIndex: 'uuId',
    hideInSearch: true,
  },
  {
    title: '演练气象事件信息',
    dataIndex: 'info',
    hideInSearch: true,
  },
  {
    title: '气象类型',
    dataIndex: 'typeCode',
    hideInTable: true,
    valueEnum: {
      ...typeCodeEnum.value,
    },
  },
  {
    title: '响应等级',
    dataIndex: 'levelCode',
    hideInTable: true,
    valueEnum: {
      ...levelCodeEnum.value,
    },
  },
  {
    title: '信息接收对象',
    dataIndex: 'drillProjectVOS',
    hideInSearch: true,
  },
  {
    title: '推送次数',
    dataIndex: 'pushCount',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
  },
]);

const modalColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '推送人',
    dataIndex: 'pushBy',
    hideInSearch: true,
  },
  {
    title: '推送总数',
    dataIndex: 'totalCount',
    hideInSearch: true,
  },
  {
    title: '推送成功数',
    dataIndex: 'successCount',
    hideInSearch: true,
  },
  {
    title: '推送失败数',
    dataIndex: 'failCount',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    width: 160,
  },
]);

const pushColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    hideInSearch: true,
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    hideInSearch: true,
  },
  {
    title: '设备类型',
    dataIndex: 'deviceTypeLabel',
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    hideInSearch: true,
  },
  {
    title: '推送结果',
    dataIndex: 'pushStatus',
    hideInSearch: true,
  },
  {
    title: '状态',
    dataIndex: 'onlineStatus',
    hideInSearch: true,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '',
    type: 'number',
    field: 'details',
  },
]);

const { FormModal, open } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const { FormModal: FormModal2, open: open2 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const { FormModal: FormModal3, open: open3 } = useFormModal({
  size: 'small',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const code = ref();

const onView = async (record: any) => {
  code.value = record.id;
  open({
    title: '推送记录',
    modalType: 'disabled',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  pushStatus: '',
  drillPushTotalId: '',
});
const onModalView = async (record: any) => {
  queryParams.value = {
    ...queryParams.value,
    ...pick(record, ['drillPushTotalId', 'pushStatus']),
  };
  open2({
    title: '气象演练推送设备列表',
    modalType: 'disabled',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const onMessage = async (record: any) => {
  if (record.jsonData) {
    if (record.jsonData.indexOf('{') != -1) {
      messageData.value = JSON.parse(record.jsonData);
    } else {
      messageData.value = record.jsonData;
    }
  } else {
    messageData.value = {};
  }
  open3({
    title: '报文',
    modalType: 'disabled',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await deleteFastWeatherWarning(selectKeys.value);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const _pushTotalLog = async (params: any) => {
  const res = await pushTotalLog(code.value, params);
  const { rows, total } = res;
  return {
    rows,
    total,
  };
};

const _weatherlogList = async () => {
  const res = await weatherlogList(queryParams.value);
  const { rows, total } = res;
  return {
    rows,
    total,
  };
};
</script>

<style scoped lang="scss">
.eewMessage {
  > div {
    margin-bottom: 10px;
    display: flex;
    text-align: left;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
